package com.xhsj.user.lsm.web;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xhsj.user.hr.system.service.TbGlobalUserService;
import com.xhsj.user.lsm.entity.TbContractApply;
import com.xhsj.user.lsm.model.MyContractApply;
import com.xhsj.user.lsm.service.TbBadgesUseApplyService;
import com.xhsj.user.lsm.service.TbContractApplyService;
import com.xhsj.user.utils.IdGen;
import com.xhsj.user.utils.Message;
import com.xhsj.user.utils.StringUtils;
import com.xhsj.user.utils.UserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;


/**
 * <p>
 * 合同申请表 前端控制器
 * </p>
 *
 * @author suxiaolin
 * @since 2020-05-11
 */
@Slf4j
@Api(tags = "合同申请表")
@RestController
@RequestMapping("/process/tbContractApply")
public class TbContractApplyController {

	@Autowired
    public TbContractApplyService service;

	@Autowired
	public TbBadgesUseApplyService tbBadgesUseApplyService;

	@Autowired
	private TbGlobalUserService tbGlobalUserService;


    //角色名称 商务经理
    @Value("${rolekeyname.roleBusinessName}")
    private String roleBusinessName;

    //角色名称 法务经理
    @Value("${rolekeyname.roleLegalName}")
    private String roleLegalName;

    //角色名称 财务
    @Value("${rolekeyname.financeRoleName}")
    private String financeRoleName;

    //角色名称 综合管理部
    @Value("${rolekeyname.integratedManager}")
    private String integratedManager;

    //角色名称 总经理
    @Value("${rolekeyname.generalManager}")
    private String generalManager;


    @ApiOperation(value = "合同申请表,保存/修改", notes = "合同申请表,保存和修改方法")
	@RequestMapping(value = "/save", method = RequestMethod.POST)
    //@PreAuthorize("hasAuthority('tb:contract:apply:edit')")
	public Message save(@RequestBody TbContractApply data){
    	try {
			data.setSubmitStatus(1);
    		service.saveContractApply(data);
			return Message.success("成功");
		} catch (Exception e) {
			log.error("保存失败:{}",e);
        	return Message.error(1,"失败");
		}

	}

	@ApiOperation(value = "合同流程启动", notes = "合同流程启动")
	@RequestMapping(value = "/startProcess", method = RequestMethod.POST)
	public Message startProcess(@RequestBody TbContractApply data){
		try {
			data.setSubmitStatus(2);
			service.startProcess(data);
			return Message.success("成功",data);
		} catch (Exception e) {
			log.error("失败:{}",e);
			return Message.error(1,e.getMessage());
		}

	}

    @ApiImplicitParam(name = "data", value = "", required = true, dataType = "data")
    @ApiOperation(value = "合同流程-重新提交", notes = "合同流程-重新提交")
    @RequestMapping(value = "/returnCommitAudit", method = RequestMethod.POST)
    public Message returnCommitAudit(@RequestBody Map<String,Object> data){
        try {
            if(StringUtils.toInteger(data.get("status"))==0) {
                //得到部门领导
                String leader = String.valueOf(tbGlobalUserService.getLeaderId(StringUtils.toLong(data.get("proposerId"))));
//            String leader = tbGlobalUserService.getLeaderByUserId(StringUtils.toLong(data.get("proposerId")));
                if (StringUtils.isBlank(leader) || leader == "null") {
                    throw new Exception("部门领导不存在,请联系管理员添加相关人员");
                }
                data.put("userId",Arrays.asList(String.valueOf(leader).split(",")));
            }
            service.returnCommitAudit(data);
            return Message.success("保存成功");
        } catch (Exception e) {
            log.error("保存失败:{}",e);
            // TODO: handle exception
            return Message.error(e.getMessage());

        }
    }

//    @ApiImplicitParam(name = "data", value = "", required = true, dataType = "data")
//    @ApiOperation(value = "合同流程-重新保存", notes = "合同流程-重新提交")
//    @RequestMapping(value = "/returnCommitAuditSave", method = RequestMethod.POST)
//    public Message returnCommitAuditSave(@RequestBody Map<String,Object> data){
//        try {
//            service.returnCommitAudit(data);
//            return Message.success("保存成功");
//        } catch (Exception e) {
//            log.error("保存失败:{}",e);
//            // TODO: handle exception
//            return Message.error("保存失败");
//
//        }
//    }

	@ApiImplicitParam(name = "data", value = "", required = true, dataType = "data")
	@ApiOperation(value = "合同流程-主管审核提交", notes = "合同流程-主管审核提交")
	@RequestMapping(value = "/contractDirectorAudit", method = RequestMethod.POST)
	public Message contractDirectorAudit(@RequestBody Map<String,Object> data){
		try {
            if(StringUtils.toInteger(data.get("status"))==0) {
                //根据角色名查找角色
                List<String> roleListByRoleName = tbGlobalUserService.getRoleListByRoleName(roleBusinessName);
                if (roleListByRoleName !=null && roleListByRoleName.size() == 0) {
                    return Message.error(1,"下一节点审核角色不存在,请联系管理员添加相关人员");
                }
                // 检查角色下是否有用户
                tbGlobalUserService.checkRoleUserId(roleBusinessName,"市场营销经理");
                data.put("roleIds",roleListByRoleName);
            }else if(StringUtils.toInteger(data.get("status"))==1){
                // 检查用户是否存在
                tbGlobalUserService.checkUserId(data.get("proposerId"));
                data.put("userId",Arrays.asList(String.valueOf(data.get("proposerId")).split(",")));
//                // 处理采购合同审核退回
//                service.handleBackPurchaseOrder(data);
            }
            service.contractExecProcess(data);
			return Message.success("保存成功");
		} catch (Exception e) {
			log.error("保存失败:{}",e);
			// TODO: handle exception
			return Message.error(e.getMessage());

		}
	}


    @ApiImplicitParam(name = "data", value = "", required = true, dataType = "data")
    @ApiOperation(value = "合同流程-商务主管审核提交", notes = "合同流程-商务主管审核提交")
    @RequestMapping(value = "/contractBusinessAudit", method = RequestMethod.POST)
    public Message contractBusinessAudit(@RequestBody Map<String,Object> data){
        try {
            if(StringUtils.toInteger(data.get("status"))==0) {
                Integer contractType = StringUtils.toInteger(data.get("contractType"));
                // 采购合同
                if (contractType == 1) {
                    data.put("status",4);
                    List<String> roleListByRoleName = tbGlobalUserService.getRoleListByRoleName(financeRoleName);
                    if (roleListByRoleName !=null && roleListByRoleName.size() == 0) {
                        return Message.error(1,"下一节点审核角色不存在,请联系管理员添加相关人员");
                    }
                    // 检查角色下是否有用户
                    tbGlobalUserService.checkRoleUserId(financeRoleName,"财务主管");
                    data.put("roleIds",roleListByRoleName);
                }else{
                    //根据角色名查找角色
                    List<String> roleListByRoleName = tbGlobalUserService.getRoleListByRoleName(roleLegalName);
                    if (roleListByRoleName !=null && roleListByRoleName.size() == 0) {
                        return Message.error(1,"下一节点审核角色不存在,请联系管理员添加相关人员");
                    }
                    // 检查角色下是否有用户
                    tbGlobalUserService.checkRoleUserId(roleLegalName,"法务顾问");
                    data.put("roleIds",roleListByRoleName);
                }

            }else if(StringUtils.toInteger(data.get("status"))==1){
                // 检查用户是否存在
                tbGlobalUserService.checkUserId(data.get("proposerId"));
                data.put("userId",Arrays.asList(String.valueOf(data.get("proposerId")).split(",")));
//                // 处理采购合同审核退回
//                service.handleBackPurchaseOrder(data);
            }
            service.contractExecProcess(data);
            return Message.success("保存成功");
        } catch (Exception e) {
            log.error("保存失败:{}",e);
            // TODO: handle exception
            return Message.error(e.getMessage());
        }
    }



    /**
     * 财务审核
     * @author 苏小林
     * @date 2020/5/29 13:49
     * @param: data
     * @return: com.xhsj.badges.utils.Message
     */
    @ApiImplicitParam(name = "data", value = "", required = true, dataType = "data")
    @ApiOperation(value = "合同流程-财务审核提交", notes = "合同流程-财务审核提交")
    @RequestMapping(value = "/contractFnanceAudit", method = RequestMethod.POST)
    public Message contractFnanceAudit(@RequestBody Map<String,Object> data){
        try {
            if(StringUtils.toInteger(data.get("status"))==0) {
                //根据角色名查找角色
                List<String> roleListByRoleName = tbGlobalUserService.getRoleListByRoleName(roleLegalName);
                if (roleListByRoleName !=null && roleListByRoleName.size() == 0) {
                    return Message.error(1,"下一节点审核角色不存在,请联系管理员添加相关人员");
                }
                // 检查角色下是否有用户
                tbGlobalUserService.checkRoleUserId(roleLegalName,"法务顾问");
                data.put("roleIds",roleListByRoleName);

            }else if(StringUtils.toInteger(data.get("status"))==1){
                // 检查用户是否存在
                tbGlobalUserService.checkUserId(data.get("proposerId"));
                data.put("userId",Arrays.asList(String.valueOf(data.get("proposerId")).split(",")));
//                // 处理采购合同审核退回
//                service.handleBackPurchaseOrder(data);
            }
            service.contractExecProcess(data);
            return Message.success("保存成功");
        } catch (Exception e) {
            log.error("保存失败:{}",e);
            // TODO: handle exception
            return Message.error(e.getMessage());
        }
    }

    @ApiImplicitParam(name = "data", value = "", required = true, dataType = "data")
    @ApiOperation(value = "合同流程-法务审核提交", notes = "合同流程-法务审核提交")
    @RequestMapping(value = "/contractLegalAudit", method = RequestMethod.POST)
    public Message contractLegalAudit(@RequestBody Map<String,Object> data){
        try {
            if(StringUtils.toInteger(data.get("status"))==0) {
                //根据角色名查找角色
                List<String> roleListByRoleName = tbGlobalUserService.getRoleListByRoleName(generalManager);
                if (roleListByRoleName !=null && roleListByRoleName.size() == 0) {
                    return Message.error(1,"下一节点审核角色不存在,请联系管理员添加相关人员");
                }
                // 检查角色下是否有用户
                tbGlobalUserService.checkRoleUserId(generalManager,"总经理");
                data.put("roleIds",roleListByRoleName);
            }else if(StringUtils.toInteger(data.get("status"))==1){
                // 检查用户是否存在
                tbGlobalUserService.checkUserId(data.get("proposerId"));
                data.put("userId",Arrays.asList(String.valueOf(data.get("proposerId")).split(",")));
//                // 处理采购合同审核退回
//                service.handleBackPurchaseOrder(data);
            }
            service.contractExecProcess(data);
            return Message.success("保存成功");
        } catch (Exception e) {
            log.error("保存失败:{}",e);
            // TODO: handle exception
            return Message.error(e.getMessage());

        }
    }

    @ApiImplicitParam(name = "data", value = "", required = true, dataType = "data")
    @ApiOperation(value = "合同流程-总经理审核提交", notes = "合同流程-法务审核提交")
    @RequestMapping(value = "/contractGeneralManagerAudit", method = RequestMethod.POST)
    public Message contractGeneralManagerAudit(@RequestBody Map<String,Object> data){
        try {
            if(StringUtils.toInteger(data.get("status"))==0) {
                //根据角色名查找角色
                List<String> roleListByRoleName = tbGlobalUserService.getRoleListByRoleName(integratedManager);
                if (roleListByRoleName !=null && roleListByRoleName.size() == 0) {
                    return Message.error(1,"下一节点审核角色不存在,请联系管理员添加相关人员");
                }
                // 检查角色下是否有用户
                tbGlobalUserService.checkRoleUserId(integratedManager,"综合管理部负责人");
                data.put("roleIds",roleListByRoleName);
            }else if(StringUtils.toInteger(data.get("status"))==1){
                // 检查用户是否存在
                tbGlobalUserService.checkUserId(data.get("proposerId"));
                data.put("userId",Arrays.asList(String.valueOf(data.get("proposerId")).split(",")));
//                // 处理采购合同审核退回
//                service.handleBackPurchaseOrder(data);
            }
            service.contractGeneralManagerAudit(data);
            return Message.success("保存成功");
        } catch (Exception e) {
            log.error("保存失败:{}",e);
            // TODO: handle exception
            return Message.error(e.getMessage());
        }
    }

    @ApiImplicitParam(name = "data", value = "", required = true, dataType = "data")
    @ApiOperation(value = "合同流程-综合管理部审核提交", notes = "合同流程-综合管理部审核提交")
    @RequestMapping(value = "/contractIntegratedManagementAudit", method = RequestMethod.POST)
    public Message contractIntegratedManagementAudit(@RequestBody Map<String,Object> data){
        try {
            if(StringUtils.toInteger(data.get("status"))==0) {
                //根据角色名查找角色
                List<String> roleListByRoleName = tbGlobalUserService.getRoleListByRoleName(roleLegalName);
                if (roleListByRoleName !=null && roleListByRoleName.size() == 0) {
                    return Message.error(1,"下一节点审核角色不存在,请联系管理员添加相关人员");
                }
                // 检查角色下是否有用户
                tbGlobalUserService.checkRoleUserId(roleLegalName,"法务顾问");
                data.put("roleIds",roleListByRoleName);
            }else if(StringUtils.toInteger(data.get("status"))==1){
                // 检查用户是否存在
                tbGlobalUserService.checkUserId(data.get("proposerId"));
                data.put("userId",Arrays.asList(String.valueOf(data.get("proposerId")).split(",")));
//                // 处理采购合同审核退回
//                service.handleBackPurchaseOrder(data);
            }else if (StringUtils.toInteger(data.get("status"))==3) {
                // 处理采购合同审核退回
//                service.handleBackPurchaseOrder(data);
            }
            service.contractIntegratedManagementAudit(data);
            return Message.success("保存成功");
        } catch (Exception e) {
            log.error("保存失败:{}",e);
            // TODO: handle exception
            return Message.error(e.getMessage());
        }
    }

    @ApiImplicitParam(name = "data", value = "", required = true, dataType = "data")
    @ApiOperation(value = "合同流程-综合管理部审核保存", notes = "合同流程-综合管理部审核保存")
    @RequestMapping(value = "/contractIntegratedManagementAuditSave", method = RequestMethod.POST)
    public Message contractIntegratedManagementAuditSave(@RequestBody Map<String,Object> data){
        try {
            service.contractIntegratedManagementAudit(data);
            return Message.success("保存成功");
        } catch (Exception e) {
            log.error("保存失败:{}",e);
            // TODO: handle exception
            return Message.error("保存失败");
        }
    }

    @ApiImplicitParam(name = "data", value = "", required = true, dataType = "data")
    @ApiOperation(value = "合同流程-法务复审审核提交", notes = "合同流程-法务复审审核提交")
    @RequestMapping(value = "/contractLegalReviewAudit", method = RequestMethod.POST)
    public Message contractLegalReviewAudit(@RequestBody Map<String,Object> data){
        try {
            if(StringUtils.toInteger(data.get("status"))==1) {
                //综合管理部
                List<String> roleListByRoleName = tbGlobalUserService.getRoleListByRoleName(integratedManager);
                if (roleListByRoleName !=null && roleListByRoleName.size() == 0) {
                    return Message.error(1,"下一节点审核角色不存在,请联系管理员添加相关人员");
                }
                // 检查角色下是否有用户
                tbGlobalUserService.checkRoleUserId(integratedManager,"综合管理部负责人");
                data.put("roleIds",roleListByRoleName);
            }
            service.contractLegalReviewAudit(data);
            return Message.success("保存成功");
        } catch (Exception e) {
            log.error("保存失败:{}",e);
            // TODO: handle exception
            return Message.error(e.getMessage());
        }
    }

    @ApiImplicitParam(name = "data", value = "", required = true, dataType = "data")
    @ApiOperation(value = "合同流程-审批记录", notes = "合同流程-审批记录")
    @RequestMapping(value = "/auditRecordList", method = RequestMethod.POST)
    public Message auditRecordList(@RequestBody Map<String,Object> data){
        try {
            if(StringUtils.isBlank(data.get("dataId"))) {
                return Message.error(1,"dataId业务id参数不能为空");
            }
            IPage<Map> maps = service.auditRecordList(data);
            List<Map> records = maps.getRecords();
            for (Map record: records) {
                String handlRoleId = String.valueOf(record.get("handlRoleId"));
                if(StringUtils.isNotBlank(record.get("handlRoleId"))){
                    String fullName = tbGlobalUserService.getFullNameByRoleId(handlRoleId);
                    record.put("handler",fullName);
                }
            }
            return Message.success("保存成功" ,records,maps.getTotal());
        } catch (Exception e) {
            log.error("保存失败:{}",e);
            // TODO: handle exception
            return Message.error("保存失败");
        }
    }


    @ApiOperation(value = "合同申请表删除", notes = "通过id删除合同申请表信息。")
	@RequestMapping(value = "/delete", method = RequestMethod.GET)
    //@PreAuthorize("hasAuthority('tb:contract:apply:delete')")
	public Message delete(@RequestParam(value="id") String id) {
		try {
			service.removeById(id);
        	return Message.success("成功");
		} catch (Exception e) {
			log.error("删除失败:{}",e);
            return Message.error(1,"失败");
		}

	}

	@ApiOperation(value = "批量删除", notes = "批量删除。")
	@RequestMapping(value = "/batchDelete", method = RequestMethod.POST)
	public Message batchDelete(@RequestBody List<String> list) {
		try {
			service.removeByIds(list);
    		return Message.success("成功");
		} catch (Exception e) {
    		log.error("删除失败:{}",e);
    		return Message.error(1,"失败");
		}
    }

	@ApiOperation(value = "分页查询我的合同列表", notes = "带参数查询,{\"page\": 1,\"size\": 5,......}。支持模糊查询")
	@RequestMapping(value="/findListByUserId",method = RequestMethod.POST)
    //@PreAuthorize("hasAuthority('tb:contract:apply:view')")
	public Message findListByUserId(@RequestBody Map<String,Object> data) {
        try {
            Object userId = data.get("userId");
            if (Objects.isNull(userId)) {
                return Message.error(1,"用户id不能为空");
            }
        	IPage<TbContractApply> selectPage = service.findListByUserId(data);
    		return Message.success("成功",selectPage.getRecords(),selectPage.getTotal(),selectPage.getPages());
        } catch (Exception e) {
			log.error("查询异常:{}",e);
    		return Message.error(1,"失败");
        }
	}

    @ApiOperation(value = "分页查询合同申请表list", notes = "带参数查询,{\"page\": 1,\"size\": 5,......}。支持模糊查询")
    @RequestMapping(value="/findList",method = RequestMethod.POST)
    //@PreAuthorize("hasAuthority('tb:contract:apply:view')")
    public Message findList(@RequestBody Map<String,Object> data) {
        try {
            IPage<MyContractApply> selectPage = service.selectPage(data);
            for (MyContractApply record : selectPage.getRecords()) {

                if(StringUtils.isNotBlank(record.getUserId())){
                    String fullName = tbGlobalUserService.getFullNameByUserId(record.getUserId());
                    record.setHandler(fullName);

                }else if(StringUtils.isNotBlank(record.getRoleId())){
                    String fullName = tbGlobalUserService.getFullNameByRoleId(record.getRoleId());
                    record.setHandler(fullName);
                }
            }
            return Message.success("成功",selectPage.getRecords(),selectPage.getTotal(),selectPage.getPages());
        } catch (Exception e) {
            log.error("查询异常:{}",e);
            return Message.error(1,"失败");
        }
    }


	@ApiOperation(value = "查询合同申请表所有数据list", notes = "查询合同申请表所有数据list。")
	@RequestMapping(value="/findAll",method = RequestMethod.POST)
    //@PreAuthorize("hasAuthority('tb:contract:apply:view')")
	public Message findAll(){
        return Message.success("成功",service.selectAll());
	}


	@ApiOperation(value = "通过id获取合同申请表实体类", notes = "通过id获取合同申请表实体类。")
	@RequestMapping(value="/getById",method = RequestMethod.GET)
    //@PreAuthorize("hasAuthority('tb:contract:apply:view')")
	public Message getById(@RequestParam(value="id") String id) {
    	return Message.success("成功",service.getById(id));
	}

	@ApiOperation(value = "通过id获取实体类详细信息", notes = "通过id获取实体类详细信息。")
	@RequestMapping(value="/detail",method = RequestMethod.GET)
    //@PreAuthorize("hasAuthority('tb:contract:apply:view')")
	public Message detail(@RequestParam(value="id") String id) {
    	return Message.success("成功",service.getById(id));
	}

}

